package org.looop.studio.noots.advantage;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermFreqVector;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;

public class BooksLikeThis {
	private IndexReader reader;
	private IndexSearcher searcher;
	
	public BooksLikeThis(IndexReader reader) {
		this.reader = reader;
		searcher = new IndexSearcher(reader);
	}

	public Document[] docsLike(int id, int max) throws IOException {
		Document doc = reader.document(id);
		
		String[] authors = doc.getValues("author");
		BooleanQuery authorQuery = new BooleanQuery();
		for (int i = 0; i < authors.length; i++) {
			String author = authors[i];
			authorQuery.add(new TermQuery(new Term("author", author)), false, false);
		}
		authorQuery.setBoost(2.0f);
		
		TermFreqVector vector = reader.getTermFreqVector(id, "subject");
		BooleanQuery subjectQuery = new BooleanQuery();
		for (int i = 0; i < vector.size(); i++) {
			TermQuery tq = new TermQuery(new Term("subject", vector.getTerms()[i]));
			subjectQuery.add(tq, false, false);
		}
		
		BooleanQuery likeThisQuery = new BooleanQuery();
		likeThisQuery.add(authorQuery, false, false);
		likeThisQuery.add(subjectQuery, false, false);
		
		likeThisQuery.add(new TermQuery(new Term("isbn", doc.get("isbn"))), false, false);
		System.out.println(" Query: " + likeThisQuery.toString("content"));
		
		Hits hits = searcher.search(likeThisQuery);
		int size = max;
		if(max > hits.length()) size = hits.length();
		
		Document[] docs = new Document[size];
		for(int i=0; i < size; i++){
			docs[i] = hits.doc(i);
		}
		
		return docs;
	}
}
